{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import gc\n",
    "import torch\n",
    "from internal.utils import sfm_outlier_detection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parsed_poses_file = os.path.expanduser(\"~/dataset/dbl/parsed_from_exif-sift_matching/parsed.npy\")  # produced by dji2pose.ipynb\n",
    "# [NOTE] Remember to run a `point_triangulator` if it is merged from multiple models (e.g. `hierarchical_mapper`, `model_merger`)\n",
    "sparse_model_dir = os.path.expanduser(\"~/dataset/dbl/parsed_from_exif-sift_matching/sfm_partitions-merged/final-retriangulated\")\n",
    "output_name = \"outliers_removed\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "colmap_images = sfm_outlier_detection.load(parsed_poses_file, sparse_model_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# tune the parameters untill it produces the expected results\n",
    "saver = sfm_outlier_detection.filter(\n",
    "    colmap_images,\n",
    "    output_name=output_name,\n",
    "    min_acceptable_error_limit=6.,\n",
    "    max_acceptable_error_limit=64.,\n",
    "    device=\"cuda\",  # use CUDA to speedup calculation\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "outliers_removed_model_dir = saver(\n",
    "    update_3d_points=False,  # must be True if it is used for `model_merger`\n",
    ")\n",
    "outliers_removed_model_dir"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "del saver\n",
    "gc.collect()\n",
    "torch.cuda.empty_cache()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# [Optional] Bundle adjustment\n",
    "ba_output_path = \"{}-bundle_adjusted\".format(outliers_removed_model_dir)\n",
    "os.makedirs(ba_output_path, exist_ok=True)\n",
    "print(\" \\\\\\n    \".join([\n",
    "    \"colmap\",\n",
    "    \"bundle_adjuster\",\n",
    "    \"--input_path={}\".format(outliers_removed_model_dir),\n",
    "    \"--output_path={}\".format(ba_output_path),\n",
    "    \"--BundleAdjustment.use_gpu=1\",\n",
    "]))"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
